//
//  DetailInfoViewController.m
//  CarFace
//
//  Created by dlios on 15-3-25.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "DetailInfoViewController.h"
#import "CarInfoInDetailVC.h"
#import "DetailInfoTableViewCell.h"
#import "PicFirstShow.h"
#import "PicCollectionViewCell.h"
#import "HeadPicName.h"
#import "PhotoWallViewController.h"
#import "PublicCommentViewController.h"
@interface DetailInfoViewController ()<UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UIWebViewDelegate>
@property (nonatomic, retain)UIScrollView *scrollView;
@property (nonatomic, retain)UITableView *tableView;
@property (nonatomic, retain)NSMutableArray *arr;
@property (nonatomic, retain)UIImageView *headImageView;
@property (nonatomic, retain)UILabel *carType;
@property (nonatomic, retain)UILabel *picCount;
@property (nonatomic, retain)UILabel *nameLabel;
@property (nonatomic, retain)UILabel *priceRange;
@property (nonatomic, retain)UISegmentedControl *segmentedControl;
@property (nonatomic, retain)UICollectionView *collectionView;
@property (nonatomic, retain)NSMutableArray *picFirstArr;


//详解部分属性
//@property (nonatomic, retain)UIWebView *webView;
//@property (nonatomic, retain)NSMutableArray *testArr;
//@property (nonatomic, retain)UITableView *testTableView;

//刷新
//@property(nonatomic, retain)HaveAEasyHUD *progressHud;

@end

@implementation DetailInfoViewController

- (void)dealloc
{
    [_CarId release];
    [_scrollView release];
    [_tableView release];
    [_arr release];
    [_headImageView release];
    [_carType release];
    [_picCount release];
    [_nameLabel release];
    [_priceRange release];
    [_segmentedControl release];
    [_collectionView release];
    [_picFirstArr release];
//    [_webView release];
    [super dealloc];
    
}

- (void)handleData
{
    
    /************************************** 处理详细信息数据************************************/

    
    //初始化详细信息数组
    self.arr = [NSMutableArray array];

    //获取本页面网址
    NSString *str = [NSString stringWithFormat:@"http://app.api.autohome.com.cn/autov4.6/cars/seriessummary-a2-pm2-v4.6.1-s%@-t.html",self.CarId];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        NSLog(@"成功%@",responseObject);
        NSError *error = nil;
        NSJSONSerialization *result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];
       
        
        
        //给桌面出了tabview的元素赋值
         NSDictionary *dic = [result valueForKey:@"result"];
        NSString *picStr = [dic valueForKey:@"logo"];
        picStr = [picStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSURL *url = [NSURL URLWithString:picStr];
        [self.headImageView setImageWithURL:url];
        
        self.carType.text = [dic valueForKey:@"levelname"];
        self.carType.textAlignment = NSTextAlignmentCenter;
        self.picCount.text = [NSString stringWithFormat:@"%@张图片", [dic valueForKey:@"piccount"]];
        self.picCount.textAlignment = NSTextAlignmentCenter;
        self.nameLabel.text = [dic valueForKey:@"name"];
        self.nameLabel.textAlignment = NSTextAlignmentCenter;
        self.priceRange.text = [dic valueForKey:@"fctprice"];
        self.priceRange.textAlignment = NSTextAlignmentCenter;
        
        
        //将最里层字典转化成对象类型
        NSMutableArray *array = [[result valueForKey:@"result"]valueForKey:@"enginelist"];
        for (NSDictionary *dic2 in array) {
            CarInfoInDetailVC *info = [[CarInfoInDetailVC alloc]initWithDictionary:dic2];
            [self.arr addObject:info];
            [info release];
            
        }
        
        //重新加载数据
        [self.tableView reloadData];
        

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"失败%@",error);
    }];
    
/************************************** 处理图片数据************************************/

    //初始化图片数组
    self.picFirstArr = [NSMutableArray array];
    
    //获取图片网址
    NSString *picStr = [NSString stringWithFormat:@"http://app.api.autohome.com.cn/autov4.6/cars/pics-a2-pm2-v4.6.1-ss%@-sp0-cg0-cl0-p1-s60-ft1.html",self.CarId];
    NSLog(@"%@",picStr);
    
    AFHTTPRequestOperationManager *manager2 = [AFHTTPRequestOperationManager manager];
    manager2.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager2 GET:picStr parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSError *error2 = nil;
        NSJSONSerialization *result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error2];
        NSMutableArray *array = [[result valueForKey:@"result"]valueForKey:@"defaultpiclist"];
        for (NSDictionary *dic in array) {
            PicFirstShow *picInfo = [[PicFirstShow alloc]initWithDictionary:dic];
            [self.picFirstArr addObject:picInfo];
            [picInfo release];
        }
        
        //重新加载数据
        [self.collectionView reloadData];
        
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"失败2%@",error);
    }];
  
    /**************************** 处理详解数据*****************************/
//
//    NSString *datalPress = [NSString stringWithFormat:@"http://cont.app.autohome.com.cn/autov4.6/content/news/seriesexplain-a2-pm2-v4.6.1-n%@-lz0-sp0-nt0-sa1-p3-c-fs0-cw360.html",self.CarId];
//    
//    NSURL *url = [NSURL URLWithString:datalPress];
//    NSURLRequest *request = [NSURLRequest requestWithURL:url];
//    
//    [self.webView loadRequest:request];

}



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //初始化菊花
//    self.progressHud = [[HaveAEasyHUD alloc] initOneProgressHud:self.view];
    
    /************************************** 布局综述页面************************************/
    
    self.view.backgroundColor = [UIColor magentaColor];
    
    //顶部导航栏的定制并制定方法
    
    self.segmentedControl = [[UISegmentedControl alloc]initWithItems:@[@"综述",@"图片"]];
    self.navigationItem.titleView = self.segmentedControl;
    [self.segmentedControl addTarget:self action:@selector(ClickSegmentcontrol:) forControlEvents:UIControlEventValueChanged];
    [_segmentedControl release];
    
    
    //创建scrollView的frame 为根背景视图
    self.scrollView = [[UIScrollView alloc]initWithFrame:self.view.bounds];
    self.scrollView.backgroundColor = [UIColor yellowColor];
    self.scrollView.contentSize = CGSizeMake(self.view.frame.size.width*2, 0);
    
    //scrollview的滚动方式为按页翻页
    self.scrollView.pagingEnabled = YES;
    self.scrollView.delegate = self;
    self.scrollView.bounces = NO;
    [self.view addSubview:self.scrollView];
    [_scrollView release];
   
    
    //创建顶部imageview添加到scrollview上
    self.headImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.scrollView.frame.size.width, self.scrollView.frame.size.height/3)];
    self.headImageView.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:self.headImageView];
    [_headImageView release];
    
    //在图片上添加车型和照片数量两个label;
    self.carType = [[UILabel alloc]initWithFrame:CGRectMake(0, self.headImageView.frame.size.height/10*9, self.headImageView.frame.size.width/3, self.headImageView.frame.size.height/10)];
//    self.carType.backgroundColor = [UIColor redColor];
    self.carType.font = [UIFont systemFontOfSize:14];
    self.carType.textColor = [UIColor whiteColor];
    [self.headImageView addSubview:self.carType];
    [_carType release];
    
    
     self.picCount = [[UILabel alloc]initWithFrame:CGRectMake(self.headImageView.frame.size.width/3, self.headImageView.frame.size.height/10*9, self.headImageView.frame.size.width/3, self.headImageView.frame.size.height/10)];
//    self.picCount.backgroundColor = [UIColor redColor];
    self.picCount.font = [UIFont systemFontOfSize:14];
    self.picCount.textColor = [UIColor whiteColor];
    [self.headImageView addSubview:self.picCount];
    [_picCount release];
    
    
    //图片下方添加车名和价格区间两个label
     self.nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, self.scrollView.frame.size.height/3 , self.scrollView.frame.size.width/2, self.scrollView.frame.size.height/24)];
    self.nameLabel.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:self.nameLabel];
    [_nameLabel release];
    
    
    self.priceRange = [[UILabel alloc]initWithFrame:CGRectMake(self.scrollView.frame.size.width/2, self.scrollView.frame.size.height/3 , self.scrollView.frame.size.width/2, self.scrollView.frame.size.height/24)];
    self.priceRange.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:self.priceRange];
    [_priceRange release];
  
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, self.scrollView.frame.size.height/3+self.scrollView.frame.size.height/24, self.scrollView.frame.size.width, self.scrollView.frame.size.height - self.scrollView.frame.size.height/3-self.scrollView.frame.size.height/24-113)style:UITableViewStylePlain];
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
//    self.tableView.scrollEnabled = NO;
    [self.scrollView addSubview:self.tableView];
    [_tableView release];
    
    
    
    
/************************************** 布局图片页面************************************/
    
    
    //创建collectionView
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.itemSize = CGSizeMake((self.view.frame.size.width-30)/3, 100);
    flowLayout.minimumLineSpacing = 10;
//    flowLayout.minimumInteritemSpacing = 10;
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 5, 0, 5);
    flowLayout.headerReferenceSize = CGSizeMake(self.view.frame.size.width, 40);
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(self.scrollView.frame.size.width, 0, self.scrollView.frame.size.width, self.scrollView.frame.size.height-113 ) collectionViewLayout:flowLayout];

    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.backgroundColor = [UIColor whiteColor];
   
    
    
    
    [self.collectionView registerClass:[PicCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    [self.collectionView registerClass:[HeadPicName class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"head"];

    
    [self.scrollView addSubview:self.collectionView];
    [flowLayout release];
    [_collectionView release];
    
    /*****************************布局详解页面*************************/
//        self.webView = [[UIWebView alloc]initWithFrame:CGRectMake(self.scrollView.frame.size.width*2, 0, self.scrollView.frame.size.width, self.scrollView.frame.size.height-113)];
//        self.webView.delegate = self;
////    self.webView.scrollView.delegate = self;
//        self.webView.scalesPageToFit = YES;
//        [self.scrollView addSubview:self.webView];
//        [_webView release];
    
    
    //加载数据
     [self handleData];

  
}


-(void)viewDidAppear:(BOOL)animated
{
////    NSLog(@"kkkkkkk%f",self.tableView.contentSize.height);
//    self.tableView.frame =CGRectMake(0, self.scrollView.frame.size.height/3+self.scrollView.frame.size.height/24, self.scrollView.frame.size.width, self.tableView.contentSize.height);
//    
//    self.scrollView.contentSize = CGSizeMake(self.view.frame.size.width*3, self.view.frame.size.height/3+self.view.frame.size.height/24 + self.tableView.contentSize.height);
//    
//    
    
    
}

/******************************* 图片页面scrollView方法部分**************************/

//设置分组的个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return self.picFirstArr.count;
}

//设置每个分组的item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    PicFirstShow *info = [self.picFirstArr objectAtIndex:section];
    NSArray *array = info.list;
    return array.count;
    
    
}



//设置分组的标题
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *reusableView = nil;
    if (kind == UICollectionElementKindSectionHeader) {
        HeadPicName *head = (HeadPicName *)[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"head" forIndexPath:indexPath];
        PicFirstShow *info = [self.picFirstArr objectAtIndex:indexPath.section];
        head.titleLabel.text = info.name;
        

        
        
        NSString *picCount = [NSString stringWithFormat:@"%@张",info.total];
        head.picCount.text = picCount;
        head.picCount.font = [UIFont systemFontOfSize:14];
        head.picCount.textAlignment = NSTextAlignmentLeft;
        head.picCount.textColor = [UIColor lightGrayColor];
        
        [head.showAllButton setTitle:@"查看所有" forState:UIControlStateNormal];
        head.showAllButton.tag = [info.picStyleId integerValue];



        
        
        
        /**********************给showAllButton设置方法、**************/
        [head.showAllButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
     
        reusableView = head;
        
    }
    return reusableView;
    
}


//showAllButton的方法实现
- (void)buttonClicked:(UIButton *)button
{
    //创建图片墙页面，给第图片墙页面传递地址，推出图片墙页面
    //生成地址
    NSNumber *num = [NSNumber numberWithInteger:button.tag];
    

    
    //创建页面
    PhotoWallViewController *photoWallVC = [[PhotoWallViewController alloc]init];
    
    
    //属性传值
    photoWallVC.pageStryleID = num;
    photoWallVC.carID = self.CarId;
    NSLog(@"%@,%@",num,self.CarId);
    if (button.tag == 1) {
        photoWallVC.titleName = @"车身外观";
        
    }else if (button.tag == 10)
        photoWallVC.titleName = @"中控方向盘";
    else if (button.tag == 3)
        photoWallVC.titleName = @"车厢座椅";
    else if (button.tag == 12)
        photoWallVC.titleName = @"其它细节";
    else if(button.tag == 14)
        photoWallVC.titleName = @"图解";
    
    //推出图片墙页面
    [self.navigationController pushViewController:photoWallVC animated:YES];
    [photoWallVC release];
    
}


//设置cell的样式
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    PicCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    
    
    PicFirstShow *info = [self.picFirstArr objectAtIndex:indexPath.section];
    NSDictionary *dic = [info.list objectAtIndex:indexPath.row];
    cell.dic = dic;
    
    
    
    return cell;
    
}



/******************************* 综述页面tableView 部分**************************/

//每个分区的行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    CarInfoInDetailVC *info = [self.arr objectAtIndex:section];
    NSArray *arr = info.speclist;
    return arr.count;
   
}

//cell的样式
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *str = @"tt";
    DetailInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
    if (cell == nil) {
        cell = [[[DetailInfoTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:str]autorelease];
        ;
        
    }
    
    CarInfoInDetailVC *info = [self.arr objectAtIndex:indexPath.section];
    NSDictionary *dic = [info.speclist objectAtIndex:indexPath.row];
    cell.info3 = dic;
    return cell;
    
}



//cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70;
}

//分区的个数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    
    return self.arr.count;

}


//分区顶部的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}

//设置各个分区的标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    CarInfoInDetailVC *info = [self.arr objectAtIndex:section];
    return info.name;
    
}


//点击cell推出口碑页面
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    PublicCommentViewController *pubVC = [[PublicCommentViewController alloc]init];
    CarInfoInDetailVC *info = [self.arr objectAtIndex:indexPath.section];
    NSDictionary *dic = [info.speclist objectAtIndex:indexPath.row];
    NSNumber *num = [dic valueForKey:@"id"];
    pubVC.modelTypeID = num;
    
    
    [self.navigationController pushViewController:pubVC animated:YES];
    [pubVC release];
    
}


//点击导航栏按钮的方法
- (void)ClickSegmentcontrol:(UISegmentedControl *)segmentControl
{
    [self.scrollView setContentOffset:CGPointMake(self.view.bounds.size.width *self.segmentedControl.selectedSegmentIndex, - 64) animated:YES];
    
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    CGFloat temp = (self.scrollView.contentOffset.x + 1) / self.view.bounds.size.width;
    NSString *str = [NSString stringWithFormat:@"%.0f", temp];
 NSInteger aa = [str integerValue];
    self.segmentedControl.selectedSegmentIndex = aa;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
